# encoding: utf-8

require Rails.root + "lib/em-websocket/em-websocket"
require Rails.root + "config/initializers/websocket/my_libraries"

# variable with sockets:
@a_sockets = Ws::WSocket.new

Thread.new do
  EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8081, :debug => false) do |ws|
    ws.onopen do
      Rails.logger.debug "Websocket opened"
      # Rails.logger.debug "COOKIES:\n\n\n#{ws.instance_variable_get('@handler').instance_variable_get('@request')['cookie']}"
      # create user:
      u = Ws::WsUser.new( ws )
      @a_sockets.add_socket( u )
      @a_sockets.refresh_all_users
      u.retrieve_friends(@a_sockets)
    end
    ws.onmessage do |msg|
      # Rails.logger.debug "Recieved:" + msg.inspect
      msg = JSON.parse( msg )
      processMessage( msg, ws )
    end
    ws.onclose do
      # sockets.delete_socket ws
      @a_sockets.delete_by_ws( ws )
      Rails.logger.debug "Websocket closed"
    end
    ws.onerror do |e|
      Rails.logger.error "Error on websocket: #{e.message}"
    end
  end
end